package com.yida.common.core.utils.memory;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

/**
 * @author Administrator
 * @date 2023/11/13
 */
public class MemoryUtils {

    /**
     * 获取运行内存模块
     * 
     * @return MemoryMXBean
     */
    public static MemoryMXBean getMemoryBean() {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        return memoryMXBean;
    }

    /**
     * 获取内存使用情况
     * 
     * @return MemoryUsage
     */
    public static MemoryUsage getMemoryUsage() {
        return getMemoryBean().getHeapMemoryUsage();
    }

    /**
     * 获取使用内存信息(bytes)
     * 
     * @return Long
     */
    public static Long getUsedMemoryInfo() {
        return getMemoryUsage().getUsed();
    }

    /**
     * 获取应用初始化内存(bytes)
     * 
     * @return Long
     */
    public static Long getInitMemoryInfo() {
        return getMemoryUsage().getInit();
    }

    /**
     * 获取当前最大内存(bytes)
     * 
     * @return Long
     */
    public static Long getMaxMemoryInfo() {
        return getMemoryUsage().getMax();
    }

    /**
     * 可读性单位换算
     * 
     * @param bytes
     * @return String
     */
    public static String convertMemorySize(long bytes) {
        int unit = 1024;
        if (bytes < unit) {
            return bytes + " B";
        }
        int exp = (int)(Math.log(bytes) / Math.log(unit));
        String pre = "KMGTPE".charAt(exp - 1) + "B";
        return String.format("%.1f %s", bytes / Math.pow(unit, exp), pre);
    }

    public static void main(String[] args) {
        System.out.println(MemoryUtils.getMaxMemoryInfo());
        System.out.println(MemoryUtils.getMaxMemoryInfo() / 1024 / 1024 / 1024);
        System.out.println(convertMemorySize(MemoryUtils.getMaxMemoryInfo()));
    }

}
